﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;

namespace WinApp
{
    public partial class FormMain : Form
    {
        private long mFlag; //0 is stop, 1 is listening

        private long mIndex;
        
        private HttpListener mHttpListener;

        public FormMain()
        {
            InitializeComponent();

            mFlag = 1;
        }

        private void buttonListen_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbListenUrl.Text))
            {
                return;
            }

            if (!HttpListener.IsSupported)
            {
                MessageBox.Show("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }

            StartListen();            
        }

        private void StartListen()
        {
            string prefix = tbListenUrl.Text;

            //start http listener
            mHttpListener = new HttpListener();
            mHttpListener.Prefixes.Add(prefix);
            mHttpListener.Start();

            listBoxInfo.Items.Clear();
            listBoxInfo.Items.Add("Listening at: " + prefix);           

            ThreadPool.QueueUserWorkItem((state) => {
                
                mFlag = Interlocked.Read(ref mFlag);
                while (mFlag == 1)
                {
                    HttpListenerContext listenerContext = mHttpListener.GetContext();
                    HttpListenerRequest listenerRequest = listenerContext.Request;
                    HttpListenerResponse listenerResponse = listenerContext.Response;

                    if (listBoxInfo.InvokeRequired)
                    {
                        listBoxInfo.Invoke((Action)(() => {
                            listBoxInfo.Items.Add(listenerRequest.RawUrl);
                        }));
                    }

                    //construct a response
                    string responseText = "Hello JobsDB" + (++mIndex);

                    byte[] responseData = Encoding.UTF8.GetBytes(responseText);

                    listenerResponse.ContentLength64 = responseData.Length;
                    listenerResponse.OutputStream.Write(responseData, 0, responseData.Length);
                    listenerResponse.OutputStream.Close();
                }                
            });
        }


        private void CloseListener()
        {
            try
            {
                Interlocked.Exchange(ref mFlag, 0);

                if (mHttpListener != null)
                {
                    mHttpListener.Close();
                    mHttpListener = null;
                }
            }
            catch
            {

            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            CloseListener();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {            
            if (MessageBox.Show("Are you sure close?", "Information", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CloseListener();
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}
